package com.google.code.pdfbrick;

import static java.lang.System.out;

import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;

import com.google.code.pdfbrick.engine.CommandExecutor;
import com.google.code.pdfbrick.engine.base.Executable;
import com.google.code.pdfbrick.engine.constant.CommandConstant;
import com.google.code.pdfbrick.merger.MergeCommand;
import com.google.code.pdfbrick.splitter.SplitCommand;

/**
 * @author Johny Huang
 * @date 2009-3-7
 */
public class PDFBrick {
	
	private static CommandExecutor EXECUTOR=CommandExecutor.getInstance();
	
	private static List<Executable> CMD_LIST=new ArrayList<Executable>();

	public static void main(String[] args) {
		if (args != null) {
			if (args.length > 0) {
				String opt = args[0];
				PDFBrick brick = new PDFBrick();
				if (args[0].equals(CommandConstant.HELP)) {
					PDFBrick.printHelp();
				}
				if(args.length >=3){
					//avoiding a space in the file path.
					int length=args.length;
					StringBuffer sBuffer=new StringBuffer(args[2]);
					for(int i=3;i<length;i++){
						sBuffer.append(args[i]);
					}
					args[2]=sBuffer.toString();
					
					if(opt.equals(CommandConstant.MERGE)){
						brick.merge(args[1],args[2]);
					}else if(opt.equals(CommandConstant.SPLIT)){
						brick.split(args[1], args[2]);
					}else{
						PDFBrick.printHelp();
					}
				}
			}
		}
	}

	public static void printHelp() {
		Formatter formatter=new Formatter();
		String fmtStr="%s      %s\n";
		formatter.format(fmtStr, CommandConstant.MERGE,"to merge the PDF");		
		formatter.format(fmtStr, CommandConstant.SPLIT,"to split the PDF");
		out.println(formatter.format(fmtStr, CommandConstant.HELP,"print this help message"));
		
		formatter.close();
	}

	public void split(String... args) {
		long startTime=System.currentTimeMillis();
		addCommand(new SplitCommand(args));
		execute();
		long timeUsed=System.currentTimeMillis()-startTime;
		out.println("Time used:"+timeUsed+"ms");
	}

	public void merge(String... args) {
		long startTime=System.currentTimeMillis();
		addCommand(new MergeCommand(args));
		execute();
		long timeUsed=System.currentTimeMillis()-startTime;
		out.println("Time used:"+timeUsed+"ms");
	}
	
	private void addCommand(Executable cmd){
		CMD_LIST.add(cmd);
	}
	
	private void execute(){
		EXECUTOR.setCommandList(CMD_LIST);
		EXECUTOR.executeAll();
	}
}
